let constant = require("./../../util/constant")
let CustomMutex = require("./custom_mutex")

const log = require("../../util/loginfo").getInstand;
const User = require('./user');

class ThreadSafeUserList {
    constructor() {
        this._userMap = new Map();
        this._mutex = new CustomMutex();
        this._onlinePlayerCount = 0;
        this._onlineRobotCount = 0;
    }

    // 获取在线玩家数量
    get onlinePlayerCount() {
        return this._onlinePlayerCount;
    }

    // 获取在线机器人数量
    get onlineRobotCount() {
        return this._onlineRobotCount;
    }

    // 执行写操作（互斥锁）
    async _writeOperation(operation) {
        const release = await this._mutex.acquire();
        try {
            return await operation();
        } finally {
            release();
        }
    }

    // 执行读操作
    async _readOperation(operation) {
        const release = await this._mutex.acquire();
        try {
            return await operation();
        } finally {
            release();
        }
    }

    // 添加用户（线程安全）
    async addUser(userInfo, socket, isRobot = false) {
        return await this._writeOperation(async () => {
            const userId = userInfo.Id;

            if (this._userMap.has(userId)) {
                const user = this._userMap.get(userId)
                log.info(`return User (${userId}) already exist user sign ${user._sign} `);
                return user
            }

            // 创建 User 对象
            const user = new User(userInfo, socket);
            this._userMap.set(userId, user);
            this._onlinePlayerCount++;

            if (isRobot) {
                this._onlineRobotCount++;
            }

            log.info(`用户 ${userId} (${user._nickname}) 添加成功，sign: ${user._sign}, 当前在线: ${this._onlinePlayerCount}, 机器人: ${this._onlineRobotCount}`);
            return user;
        });
    }

    // 获取用户（线程安全）
    async getUser(userId) {
        return await this._readOperation(() => {
            return this._userMap.get(userId) || null;
        });
    }

    // 删除用户（线程安全）
    async removeUser(userId) {
        return await this._writeOperation(async () => {
            const user = this._userMap.get(userId);
            if (!user) {
                log.warn(`尝试删除不存在的用户: ${userId}`);
                return false;
            }

            this._userMap.delete(userId);
            this._onlinePlayerCount = Math.max(0, this._onlinePlayerCount - 1);

            if (user._Robot) {
                this._onlineRobotCount = Math.max(0, this._onlineRobotCount - 1);
            }

            log.info(`用户 ${userId} (${user._nickname}) 删除成功，当前在线: ${this._onlinePlayerCount}, 机器人: ${this._onlineRobotCount}`);
            return true;
        });
    }

    // 检查用户是否存在（线程安全）
    async hasUser(userId) {
        return await this._readOperation(() => {
            return this._userMap.has(userId);
        });
    }

    // 获取所有用户ID（线程安全）
    async getAllUserIds() {
        return await this._readOperation(() => {
            return Array.from(this._userMap.keys());
        });
    }

    // 获取用户数量（线程安全）
    async getSize() {
        return await this._readOperation(() => {
            return this._userMap.size;
        });
    }

    // 清空所有用户（线程安全）
    async clear() {
        return await this._writeOperation(() => {
            const count = this._userMap.size;
            this._userMap.clear();
            this._onlinePlayerCount = 0;
            this._onlineRobotCount = 0;
            log.info(`清空所有用户，共清理: ${count} 个用户`);
            return true;
        });
    }

    // 获取统计信息（线程安全）
    async getStats() {
        return await this._readOperation(() => {
            return {
                total: this._userMap.size,
                players: this._onlinePlayerCount,
                robots: this._onlineRobotCount,
                humanPlayers: this._onlinePlayerCount - this._onlineRobotCount
            };
        });
    }

    // 原子更新用户分数（线程安全）
    async atomicUpdateScore(userId, delta) {
        return await this._writeOperation(async () => {
            const user = this._userMap.get(userId);
            if (!user) return { success: false, error: '用户不存在' };

            const oldScore = user._score;
            const result = user.addgold(delta);

            if (result) {
                log.info(`用户 ${userId} 分数更新: ${oldScore} -> ${user._score} (变化: ${delta})`);
                return {
                    success: true,
                    oldScore,
                    newScore: user._score
                };
            } else {
                log.warn(`用户 ${userId} 分数更新失败: 余额不足`);
                return {
                    success: false,
                    error: '余额不足',
                    oldScore,
                    newScore: user._score
                };
            }
        });
    }

    // 原子更新用户钻石（线程安全）
    async atomicUpdateDiamond(userId, delta) {
        return await this._writeOperation(async () => {
            const user = this._userMap.get(userId);
            if (!user) return { success: false, error: '用户不存在' };

            const oldDiamond = user._diamond;
            const result = user.adddiamond(delta);

            if (result) {
                log.info(`用户 ${userId} 钻石更新: ${oldDiamond} -> ${user._diamond} (变化: ${delta})`);
                return {
                    success: true,
                    oldDiamond,
                    newDiamond: user._diamond
                };
            } else {
                log.warn(`用户 ${userId} 钻石更新失败: 余额不足`);
                return {
                    success: false,
                    error: '余额不足',
                    oldDiamond,
                    newDiamond: user._diamond
                };
            }
        });
    }

    // 更新用户游戏状态（线程安全）
    async updateUserGameState(userId, gameId, roomId, tableId, seatId) {
        return await this._writeOperation(async () => {
            const user = this._userMap.get(userId);
            if (!user) return false;

            if (gameId !== undefined) user.loginGame(gameId);
            if (roomId !== undefined) user.loginRoom(roomId);
            if (tableId !== undefined) user.loginTable(tableId);
            if (seatId !== undefined) user.loginSeat(seatId);

            log.info(`用户 ${userId} 游戏状态更新: 游戏=${gameId}, 房间=${roomId}, 桌子=${tableId}, 座位=${seatId}`);
            return true;
        });
    }

    // 重置用户游戏状态（线程安全）
    async resetUserGameState(userId) {
        return await this._writeOperation(async () => {
            const user = this._userMap.get(userId);
            if (!user) return false;

            user.resetGame();
            log.info(`用户 ${userId} 游戏状态已重置`);
            return true;
        });
    }

    // 获取用户游戏信息（线程安全）
    async getUserGameInfo(userId) {
        return await this._readOperation(() => {
            const user = this._userMap.get(userId);
            if (!user) return null;

            return {
                gameId: user.getGameId(),
                roomId: user.getRoomId(),
                tableId: user.getTable(),
                seatId: user.getSeat(),
                score: user.getScore(),
                diamond: user.getDiamond()
            };
        });
    }

    // 查找用户（线程安全）
    async findUser(predicate) {
        return await this._readOperation(() => {
            for (const [userId, user] of this._userMap.entries()) {
                if (predicate(user, userId)) {
                    return user;
                }
            }
            return null;
        });
    }

    // 过滤用户（线程安全）
    async filterUsers(predicate) {
        return await this._readOperation(() => {
            const result = [];
            for (const [userId, user] of this._userMap.entries()) {
                if (predicate(user, userId)) {
                    result.push(user);
                }
            }
            return result;
        });
    }

    // 批量获取用户信息（线程安全）
    async getUsersInfo(userIds) {
        return await this._readOperation(() => {
            const result = {};
            for (const userId of userIds) {
                const user = this._userMap.get(userId);
                if (user) {
                    result[userId] = {
                        nickname: user._nickname,
                        score: user._score,
                        diamond: user._diamond,
                        gameId: user.getGameId(),
                        isRobot: user._Robot
                    };
                }
            }
            return result;
        });
    }

    // 遍历所有用户执行操作（线程安全）
    async forEach(callback) {
        return await this._readOperation(() => {
            this._userMap.forEach((user, userId) => {
                callback(user, userId);
            });
        });
    }

    // 获取所有在线用户的基本信息（线程安全）
    async getAllUsersBasicInfo() {
        return await this._readOperation(() => {
            const result = [];
            for (const [userId, user] of this._userMap.entries()) {
                result.push({
                    userId: userId,
                    nickname: user._nickname,
                    score: user._score,
                    diamond: user._diamond,
                    gameId: user.getGameId(),
                    isRobot: user._Robot,
                    online: true
                });
            }
            return result;
        });
    }

    // 清理不活跃（线程安全）s
    async cleanupInactiveUsers(inactiveTime = 35000) {
        return await this._writeOperation(async () => {
            const len = this._userMap.size;
            if (len <= constant.Max_Robot_Num) {
                return 0
            }

            const now = Date.now();
            const inactiveUsers = [];

            for (const [userId, user] of this._userMap.entries()) {
                // 检查用户是否长时间不活跃
                if (user._loginTime && (now - user._loginTime.getTime() > inactiveTime)) {
                    inactiveUsers.push(userId);
                }
            }
            if (inactiveUsers.length <= 0) {
                return 0
            }
            let clearNum = len - constant.Max_Robot_Num

            // 删除不活跃用户
            let cnt = 0
            for (const userId of inactiveUsers) {
                const user = this._userMap.get(userId);
                if (user) {
                    this._onlinePlayerCount--;
                    if (!user._Robot) {
                        continue
                    }
                    this._onlineRobotCount--;

                    if (user.getGameId()) {
                        var gameScoket = ServerInfo.getScoket(user.getGameId());
                        gameScoket.emit('disconnectUser', {
                            userId: loginUser.id,
                            sysCommand: "loginResult",
                            resultid: 0,
                            kick: 1,
                            msg: 'This account is kicked!'
                        });
                        log.info(`[userList] ${userId} current game id ${user.getGameId()} be kicked`);
                    } else {
                        if (user._socket && user._socket.connected) {
                            let socket = user._socket;
                            var result = { resultid: 0, kick: 1, msg: 'This account is kicked!' };
                            socket.emit('loginResult', result);
                            log.info(`[userList] ${userId} not in game be kicked`);
                        }
                    }
                    if (user._socket && user._socket.connected) {
                        user._socket.disconnect();
                    }
                    this._userMap.delete(userId);
                    ++cnt;
                }
                if (cnt >= clearNum) {
                    break
                }
            }

            if (clearNum > 0) {
                log.info(`清理了 ${clearNum} 个不活跃用户`);
            }

            return inactiveUsers.length;
        });
    }

    // 带超时的安全操作
    async withTimeout(operation, timeoutMs = 5000, operationName = 'operation') {
        const timeout = new Promise((_, reject) => {
            setTimeout(() => reject(new Error(`${operationName} 超时`)), timeoutMs);
        });

        return Promise.race([operation(), timeout]);
    }

    // 安全的用户操作（带超时）
    async safeUserOperation(operation, timeoutMs = 5000) {
        return this.withTimeout(async () => {
            return await operation();
        }, timeoutMs, '用户操作');
    }
}

module.exports = ThreadSafeUserList;